package com.balloon.springboot.datasource.persistence.dao;

import com.balloon.springboot.datasource.entity.DataSourcePropertiesBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据源持久化基础类
 */
@Component
public class DataSourceDao {

    @Autowired
    private DataSource dataSource;

    public long save(DataSourcePropertiesBean dataSourcePropertiesBean) throws SQLException {
        Connection connection = dataSource.getConnection();
        String sql = "insert into tab_data_source (driver_class_name,url,username,password,type) values(?,?,?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, dataSourcePropertiesBean.getDriverClassName());
        statement.setString(2, dataSourcePropertiesBean.getUrl());
        statement.setString(3, dataSourcePropertiesBean.getUsername());
        statement.setString(4, dataSourcePropertiesBean.getPassword());
        statement.setString(5, dataSourcePropertiesBean.getType());
        return statement.executeUpdate();
    }

    public long delete(int id) throws SQLException {
        Connection connection = dataSource.getConnection();
        String sql = "delete from tab_data_source where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        return statement.executeUpdate();
    }

    public List<DataSourcePropertiesBean> findAll() throws SQLException {
        List<DataSourcePropertiesBean> dataSourcePropertiesBeanList = new ArrayList<>();
        Connection connection = dataSource.getConnection();
        String sql = "select id,driver_class_name,url,username,password,type from tab_data_source ";
        try (PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                //遍历查询结果，每循环一次就代表一行数据
                DataSourcePropertiesBean dataSourcePropertiesBean = new DataSourcePropertiesBean();
                dataSourcePropertiesBean.setUrl(rs.getString("url"));
                dataSourcePropertiesBean.setDriverClassName(rs.getString("driver_class_name"));
                dataSourcePropertiesBean.setUsername(rs.getString("username"));
                dataSourcePropertiesBean.setPassword(rs.getString("password"));
                dataSourcePropertiesBean.setType(rs.getString("type"));
                dataSourcePropertiesBeanList.add(dataSourcePropertiesBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSourcePropertiesBeanList;
    }

}
